package org.lyq.erp.config.fileupload;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.lyq.erp.auth.employee.pojo.Employee;
import org.lyq.erp.auth.employee.service.EmployeeService;
import org.lyq.erp.config.constant.ConfigConstant;
import org.lyq.erp.config.fileupload.ftp.FtpConfig;
import org.lyq.erp.config.fileupload.ftp.FtpUtil;
import org.lyq.erp.config.fileupload.ftp.UploadUtils;
import org.lyq.erp.config.json.JSONResult;
import org.lyq.erp.config.readproperties.ReadProperties;
import org.lyq.erp.utils.format.FormatUtils;
import org.lyq.erp.utils.string.ObjectEmptyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/file")
public class FtpFileController {

	private static Logger logger = LoggerFactory.getLogger(FtpFileController.class);

	@Resource
	private EmployeeService employeeService;

	// 商家用户上传头像
	@ResponseBody
	@RequestMapping(value = "/uploadEmpHeadImg", produces = "application/json;charset=utf-8")
	public JSONResult uploadEmpHeadImg(@RequestParam("file") MultipartFile file, String userId,
			HttpServletResponse response, HttpServletRequest request) {

		response.setHeader("Access-Control-Allow-Origin", "*");

		String maxHeadImgSize = ReadProperties.getInstance().getApplicationProperties()
				.getProperty("MAX_HEADIMAGE_SIZE");

		if (file == null || file.getSize() == 0L || ObjectEmptyUtils.isEmptyString(file.getOriginalFilename()))
			return JSONResult.errorMsg("上传头像不能为空!");

		if (!checkFileSize(file.getSize(), Integer.parseInt(maxHeadImgSize), "k")) {
			return JSONResult.errorMsg("用户上传头像不能大于1M!");
		}

		// 头像图片允许上传的类型
		String picType = ReadProperties.getInstance().getApplicationProperties().getProperty("Agree_imageType");
		String originalFilename = file.getOriginalFilename();
		int start = originalFilename.lastIndexOf(".");
		String fileType = originalFilename.substring(start + 1);
		if (picType != null && fileType != null && !picType.trim().contains(fileType.trim().toUpperCase())) {
			return JSONResult.errorMsg("请上传有效格式的图片作为头像!");
		}

		String realNetworkPath = null;
		InputStream is = null;
		try {

			is = file.getInputStream();
			FtpConfig ftpConfig = FtpConfig.getInstance();

			String picNewName = UploadUtils.generateRandonFileName(originalFilename);

			StringBuilder picSavePath = new StringBuilder();
			picSavePath.append("/picture/user/");
			picSavePath.append(FormatUtils.getFormatDateTime(System.currentTimeMillis(), "yyyyMMdd"));

			realNetworkPath = FtpUtil.pictureFtpUpload(ftpConfig, picNewName, picSavePath.toString(), is);
			if (realNetworkPath != null) {

				Employee employee = new Employee();
				employee.setEmpUuid(Integer.parseInt(userId));
				employee.setEmpPictures(picSavePath.toString() + "/" + picNewName);
				employeeService.updateByPrimaryKeySelective(employee);

				Employee emp = (Employee) request.getSession().getAttribute(ConfigConstant.USER_LOGIN);
				emp.setEmpPictures(employee.getEmpPictures());

				Map<String, String> map = new HashMap<String, String>();
				map.put("picSavePath", picSavePath.toString() + picNewName);
				map.put("realNetworkPath", realNetworkPath);
				return JSONResult.ok(map);
			}
			return JSONResult.errorMsg("上次头像失败！");

		} catch (IOException e) {

			logger.error(e.getMessage());
			return JSONResult.errorMsg("上次头像失败！");
		}

	}

	// 商家商品图片
	@ResponseBody
	@RequestMapping(value = "/uploadGoodsImg", produces = "application/json;charset=utf-8")
	public JSONResult uploadGoodsImg(@RequestParam("file") MultipartFile file,
			HttpServletResponse response, HttpServletRequest request) {
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		// 头像图片允许上传的类型
		String picType = ReadProperties.getInstance().getApplicationProperties().getProperty("Agree_imageType");
		String originalFilename = file.getOriginalFilename();
		int start = originalFilename.lastIndexOf(".");
		String fileType = originalFilename.substring(start + 1);
		if (picType != null && fileType != null && !picType.trim().contains(fileType.trim().toUpperCase())) {
			return JSONResult.errorMsg("请上传有效格式的商品图片!");
		}

		String realNetworkPath = null;
		InputStream is = null;
		try {

			is = file.getInputStream();
			FtpConfig ftpConfig = FtpConfig.getInstance();

			String picNewName = UploadUtils.generateRandonFileName(originalFilename);

			StringBuilder picSavePath = new StringBuilder();
			picSavePath.append("/picture/goods/");
			picSavePath.append(FormatUtils.getFormatDateTime(System.currentTimeMillis(), "yyyyMMdd"));

			realNetworkPath = FtpUtil.pictureFtpUpload(ftpConfig, picNewName, picSavePath.toString(), is);
			if (realNetworkPath != null) {
				
				Map<String, String> map = new HashMap<String, String>();
				map.put("picSavePath", picSavePath.toString()+"/"+ picNewName);
				map.put("realNetworkPath", realNetworkPath);
				return JSONResult.ok(map);
			}
			return JSONResult.errorMsg("上传商品图片失败！");

		} catch (IOException e) {

			logger.error(e.getMessage());
			return JSONResult.errorMsg("上传商品图片失败！");
		}

	}

	/**
	 * 判断文件大小
	 *
	 * @param len  文件长度
	 * @param size 限制大小
	 * @param unit 限制单位（B,K,M,G）
	 * @return
	 */
	public static boolean checkFileSize(Long len, int size, String unit) {
		double fileSize = 0;
		if ("B".equals(unit.toUpperCase())) {
			fileSize = (double) len;
		} else if ("K".equals(unit.toUpperCase())) {
			fileSize = (double) len / 1024;
		} else if ("M".equals(unit.toUpperCase())) {
			fileSize = (double) len / 1048576;
		} else if ("G".equals(unit.toUpperCase())) {
			fileSize = (double) len / 1073741824;
		}
		if (fileSize > size) {
			return false;
		}
		return true;
	}

}
